var pickerSelf = ''
function dhcWeekPicker(options, block) {
	var self = this;
	pickerSelf = self;
	var dateDom = document.querySelector('.pickerArea')
	if(dateDom) {
		console.log('只能初始化一次');
		return;
	}
	var btnId = options.tapBtnId;
	self.initalDay = options.today;
	var dateDom = document.createElement('div');
	dateDom.setAttribute('class', 'pickerArea');
	if (btnId && btnId!= '') {
		var absPos = self.getAbsPosition(btnId);
		var popoverWith = 150 * SCALE
		var left = (absPos.centerx - popoverWith) + 'px';
		var top = absPos.top + 'px';
		dateDom.style.left = left;
		dateDom.style.top = top;
	}
	
	dateDom.innerHTML =
		'<div class="pickerHeader">' +
			'<button id="pickerCancel" class="pickerCancel">取消</button>' +
			'<div class="pickerTips">请选择周次</div>'+
			'<button id="pickerSure" class="pickerSure">确定</button>' +
		'</div>'+
		'<div class="pickerHeader">' +
			'<div id="pickerLY" class="ymBtn nurfont nur-left2"></div>' +
			'<div id="pickerLM" class="ymBtn mui-icon mui-icon-arrowleft"></div>' +
			'<div id="pickerYMText" class="pickerYMText">2021年9月</div>' +
			'<div id="pickerNM" class="ymBtn mui-icon mui-icon-arrowright"></div>' +
			'<div id="pickerNY" class="ymBtn nurfont nur-right2"></div>' +
		'</div>' +
		'<table class="pickerTable"><thead><tr>' +
			'<td>周一</td><td>周二</td><td>周三</td>' +
			'<td>周四</td><td>周五</td><td>周六</td><td>周日</td></tr></thead>' +
			'<tbody><tr></tr><tr></tr><tr></tr><tr></tr></tbody>' +
		'</table>'
	
	document.body.appendChild(dateDom);
	self.areaDom = dateDom;
	if(self.initalDay == '' || !self.initalDay) {
		self.initDays();
	}
	self.getFullWeek(self.initalDay);
	self.fillDateUI(self.startDate,self.endDate);
	//各个固定按钮点击方法
	self.setupBtnTapped(function(isHide){
		block(self.startDate,self.endDate,self.weekIndex,isHide);
	});
	block(self.startDate,self.endDate,self.weekIndex,false);
}
function dayTdTapped(){
	pickerSelf.TdDomTapped(this)
}
dhcWeekPicker.prototype.pickerShow = function(startDate, endDate) {
	var self = this;
	self.areaDom.classList.add('mui-active')
	var pickerBackDrop = document.createElement('div')
	pickerBackDrop.classList.add('pickerBackDrop')
	
	pickerBackDrop.style.opacity = 1
	document.body.insertBefore(pickerBackDrop,self.areaDom)
	if(self.startDate == startDate) {
		return;
	}
	var startDateDom = document.getElementById('picker-' + startDate);
	if(!startDateDom) {
		var tbody = self.areaDom.querySelector('tbody');
		mui('.pickerTable tbody').off('tap','td',dayTdTapped) 
		tbody.innerHTML = '';
		self.fillDateUI(startDate, endDate);
		return;
	}
	self.TdDomTapped(startDateDom);
}

dhcWeekPicker.prototype.pickerHide = function() {
	var self = this;
	self.areaDom.classList.remove('mui-active')
	var pickerBackDrop = document.body.querySelector('.pickerBackDrop')
	if (pickerBackDrop) {
		pickerBackDrop.style.opacity = 0
	}
	setTimeout(function() {
		if (pickerBackDrop) {
			document.body.removeChild(pickerBackDrop)
		}
	}, 200);
}

dhcWeekPicker.prototype.pickerChangeYM = function(type) {
	var self = this
	var arr = self.currentYM.split('-');
	var year = parseInt(arr[0]);
	var month = parseInt(arr[1]);
	if(type == 'ly') { //上年
		year -= 1;
	} else if(type == 'lm') { //上月
		if(month == 1) {
			month = 12;
			year -= 1;
		} else {
			month -= 1;
		}
	} else if(type == 'ny') { //下年
		year += 1;
	} else if(type == 'nm') { //下月
		if(month == 12) {
			month = 1;
			year += 1;
		} else {
			month += 1;
		}
	}
	var dayStr = self.outYMDStr(year,month,1);
	self.getFullWeek(dayStr);
	self.fillDateUI(self.startDate,self.endDate,true);
}

dhcWeekPicker.prototype.fillDateUI = function(startDate, endDate,isChangeYM) {
	mui('.pickerTable tbody').off('tap','td',dayTdTapped) 
	var self = this;
	self.startDate = startDate;
	self.endDate = endDate;
	self.currentYM = endDate.substr(0,7);
	var chinaYM = self.currentYM.replace('-', '年') + '月';
	var ymDom = document.getElementById('pickerYMText'); //当前年月
	self.weekIndex = self.getWeekInYear(startDate)
	ymDom.innerText = chinaYM;
	
	var arr = endDate.split("-");
	var year = parseInt(arr[0]);
	var month = parseInt(arr[1]);
	var maxDay = self.getMonthMaxDay(year, month);
	var lastMaxDay = self.getLastMonthMaxDay(year, month);
	var startIndex = self.getWeekIndex(endDate.substring(0,7) + '-01');
	if (startIndex == 0) {
		startIndex = 7
	}
	var endIndex = self.getWeekIndex(endDate.substring(0,7) + '-' + maxDay);
	if (endIndex == 0) {
		endIndex = 7
	}
	var count = startIndex + maxDay + (6 - endIndex);
	self.areaDom.style.height = 100+( count / 7 + 1)*30 + 'px';
	var html = '';
	for(var i = 0; i < count; i++) {
		if(i % 7 == 0) {
			html += '<tr>';
		}
		if(i < startIndex - 1) { //上个月的
			var dayStr = lastMaxDay - (startIndex-1) + i + 1;
			var lmonth = month - 1;
			var lyear = year;
			if(lmonth == 0) {
				lmonth = 12;
				lyear -= 1;
			}
			var idStr = '' + lyear + '-' + lmonth + '-' + dayStr;
			if(lmonth < 10) {
				idStr = '' + lyear + '-0' + lmonth + '-' + dayStr;
			}
			if (i == 0) {
				startDate = idStr
			}
			html += '<td class="abnormal" id="picker-'+idStr+'">'+dayStr+'</td>';
		} else if(i >= (startIndex-1) + maxDay) { //下个月
			var nmonth = month + 1;
			var nyear = year;
			if(nmonth == 13) {
				nmonth = 1;
				nyear += 1;
			}
			var dayStr = (i - maxDay - (startIndex-1) + 1);
			var idStr = '' + nyear + '-' + nmonth + '-0' + dayStr;
			if(nmonth < 10) {
				idStr = '' + nyear + '-0' + nmonth + '-0' + dayStr;
			}
			if (i == count -1) {
				endDate = idStr
			}
			html += '<td class="abnormal" id="picker-'+idStr+'">'+dayStr+'</td>';
		} else {
			var monthStr = month + '';
			var dayStr = (i - (startIndex-1) + 1);
			if (month < 10) {
				monthStr = '0'+month;
			}
			var idStr = '' + year +'-'+monthStr + '-' + dayStr;
			if((i - (startIndex-1) + 1) < 10) {
				idStr = '' + year +'-'+monthStr + '-0' + dayStr;
			}
			
			var classStr =""
			if (idStr == '' + self.initalDay) { //今天
				classStr = 'today'
			}
			if (i == 0) {
				startDate = idStr
			}else if (i == count -1) {
				endDate = idStr
			}
			
			html += '<td class="'+classStr+'" id="picker-'+idStr+'">'+dayStr+'</td>';
		}
		if(i % 7 == 6) {
			html += '</tr>';
		}
	}
	var areaDom = self.areaDom;
	var tbody = areaDom.querySelector('tbody');
	tbody.innerHTML = html;
	mui('.pickerTable tbody').on('tap','td',dayTdTapped) 
	//设置选中周
	if (!isChangeYM) {
		var startTd = tbody.querySelector('#picker-'+self.startDate)
		var startTr = startTd.parentNode;
		startTr.classList.add('select')
	}
	
	// var tds = tbody.querySelectorAll('td');
	// for(var i = 0; i < tds.length; i++) {
	// 	tds[i].addEventListener('tap', function() {
	// 		self.TdDomTapped(this);
	// 	});
	// }
}

dhcWeekPicker.prototype.TdDomTapped = function(tdDom) {
	var self = this;
	var classStr = tdDom.getAttribute('class');
	if(classStr && classStr.indexOf('select') != -1) { //当前周
		return;
	}
	//清除原来的
	self.clearSelectedTds();
	var currTr = tdDom.parentNode
	currTr.classList.add('select')
	self.startDate = currTr.firstChild.id.replace('picker-','')
	self.endDate = currTr.lastChild.id.replace('picker-','')
	self.weekIndex = self.getWeekInYear(self.startDate)
}

dhcWeekPicker.prototype.clearSelectedTds = function() {
	var self = this;
	var selectTr = self.areaDom.querySelector('.select');
	if (selectTr) {
		selectTr.classList.remove('select');
	}
}
dhcWeekPicker.prototype.setupBtnTapped = function(block) {
	self = this;
	var lyBtn = document.getElementById('pickerLY'); //上一年
	var lmBtn = document.getElementById('pickerLM'); //上一月
	var nmBtn = document.getElementById('pickerNM'); //下一月
	var nyBtn = document.getElementById('pickerNY'); //下一年
	var cancelBtn = document.getElementById('pickerCancel'); //取消按钮
	var sureBtn = document.getElementById('pickerSure'); //确定按钮
	
	lyBtn.addEventListener('tap', function() {//上年
		self.pickerChangeYM('ly');
	}, false)
	lmBtn.addEventListener('tap', function() {//上月
		self.pickerChangeYM('lm');
	}, false)
	nmBtn.addEventListener('tap', function() {//下月
		self.pickerChangeYM('nm');
	}, false)
	nyBtn.addEventListener('tap', function() {//下年
		self.pickerChangeYM('ny');
	}, false)
	cancelBtn.addEventListener('tap', function() {//取消
		self.pickerHide()
		block(true);
	}, false)
	sureBtn.addEventListener('tap', function() {//确定
		self.pickerHide();
		block();
	}, false)
}

dhcWeekPicker.prototype.initDays = function(){
	var self = this;
	var newDate = new Date();
	var year = newDate.getFullYear();
	var month = newDate.getMonth() + 1;
	var day = newDate.getDate();
	var str = self.outYMDStr(year,month,day);
	self.initalDay = str;
}
dhcWeekPicker.prototype.getFullWeek = function(dayStr) {
	var self = this;
	var dict = self.getYMDWithStr(dayStr)
	var cyear = dict['year'];
	var cmonth = dict['month'];
	var cday = dict['day'];
	var weekDay = self.getWeekIndex(dayStr);
	var maxDay = self.getMonthMaxDay(cyear,cmonth);
	
	if (weekDay == 0) {
		self.endDate = dayStr;
		var sday = cday - 6
		if (sday < 1) {
			cmonth -= 1;
			if (cmonth < 0) {
				cmonth = 12;
				cyear -= 1;
			}
			maxDay = self.getMonthMaxDay(cyear,cmonth);
			sday += maxDay;
		}
		self.startDate = self.outYMDStr(cyear,cmonth,sday);
		return;
	}
	var syear = cyear;
	var smonth = cmonth;
	var sday = cday;
	var sday = cday - weekDay + 1;
	cday = cday + 7 - weekDay;
	if(cday > maxDay) {
		cmonth += 1;
		cday = cday - maxDay;
		if(cmonth == 13) {
			cyear += 1;
			cmonth = 1;
		}
	}
	if(sday < 1) {
		maxDay = self.getLastMonthMaxDay(cyear,cmonth)
		sday = maxDay + sday;
		smonth -= 1;
		if(smonth == 0) {
			syear -= 1;
			smonth = 12;
		}
	}
	self.startDate = self.outYMDStr(syear, smonth, sday);
	self.endDate = self.outYMDStr(cyear, cmonth, cday);
}


dhcWeekPicker.prototype.getWeekIndex = function(dayStr) {
	var arr = dayStr.split("-");
	var year = parseInt(arr[0]);
	var month = parseInt(arr[1]) - 1;
	var day = parseInt(arr[2]);
	var originDate = new Date(year, month, day);
	return originDate.getDay()
}
dhcWeekPicker.prototype.getYMWithStr = function(dayStr){
	var arr = dayStr.split("-");
	var year = parseInt(arr[0]);
	var month = parseInt(arr[1]);
	return {'year':year,'month':month};
}
dhcWeekPicker.prototype.getYMDWithStr = function(dayStr){
	var arr = dayStr.split("-");
	var year = parseInt(arr[0]);
	var month = parseInt(arr[1]);
	var day = parseInt(arr[2]);
	return {'year':year,'month':month,'day':day};
}

dhcWeekPicker.prototype.getLastYMDict = function(year, month){
	if(month == 1) {
		month = 12;
		year -= 1;
	} else {
		month -= 1;
	}
	return {'year':year,'month':month};
}
dhcWeekPicker.prototype.getNextYMDict = function(year, month){
	if(month == 12) {
		month = 1;
		year += 1;
	} else {
		month += 1;
	}
	return {'year':year,'month':month};
}

dhcWeekPicker.prototype.getLastMonthMaxDay = function(year, month) {
	var self = this;
	if(month == 1) {
		month = 12;
		year -= 1;
	} else {
		month -= 1;
	}
	var maxDay = self.getMonthMaxDay(year, month);
	return maxDay;
}

dhcWeekPicker.prototype.getMonthMaxDay = function(year, month) {
	var maxDay = 31;
	if(month == 2) {
		maxDay = 28;
		if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
			maxDay = 29;
		}
	} else if(month == 4 || month == 6 || month == 9 || month == 11) {
		maxDay = 30;
	}
	return maxDay;
}

dhcWeekPicker.prototype.outYMStr = function(year, month) {
	var monthStr = month + '';
	if (month < 10) {
		monthStr = '0'+month;
	}
	return year + '-'+monthStr;	
}
dhcWeekPicker.prototype.outChinaYMStr = function(year, month) {
	var monthStr = month + '';
	if (month < 10) {
		monthStr = '0'+month;
	}
	return year + '年'+monthStr+'月';
}
dhcWeekPicker.prototype.outYMDStr = function(year, month,day) {
	var monthStr = month + '';
	if (month < 10) {
		monthStr = '0'+month;
	}
	var dayStr = day + '';
	if (day < 10) {
		dayStr = '0'+day;
	}
	return year + '-'+monthStr+'-'+dayStr;
}
dhcWeekPicker.prototype.outChinaMDStr = function(month,day) {
	var monthStr = month + '';
	if (month < 10) {
		monthStr = '0'+month;
	}
	var dayStr = day + '';
	if (day < 10) {
		dayStr = '0'+day;
	}
	return monthStr+'月'+dayStr+'日';
}
dhcWeekPicker.prototype.updatePickerPos = function(btnId) {
	var self  = this;
	var absPos = self.getAbsPosition(btnId);
	var popoverWith = 150 * SCALE
	var left = (absPos.centerx - popoverWith) + 'px';
	var top = absPos.top + 'px';
	self.areaDom.style.left = left;
	self.areaDom.style.top = top;
}

dhcWeekPicker.prototype.getAbsPosition = function(itemId) {
	var bodyW = parseInt(localStorage.getItem('bodyW'))
	var bodyH = parseInt(localStorage.getItem('bodyH'))
	if(itemId == null || itemId == undefined) {
		itemId = '';
	}
	var item = document.getElementById(itemId);
	if(!item) {
		return {
			'centerx': bodyW * 0.5,
			'top': bodyH * 0.4
		};
	}
	var actualLeft = item.offsetLeft + item.clientWidth * 0.5;
	var actualTop = item.offsetTop + item.clientHeight;
	var current = item.offsetParent;
	while(current !== null) {
		actualLeft += (current.offsetLeft + current.clientLeft);
		actualTop += (current.offsetTop + current.clientTop);
		current = current.offsetParent;
	}
	return {
		'centerx': actualLeft,
		'top': actualTop
	};
}
dhcWeekPicker.prototype.getWeekInYear = function(dt) {
	var d1 = new Date(dt);
	var d2 = new Date(dt);
	d2.setMonth(0);
	d2.setDate(1);
	var rq = d1-d2;
	var days = Math.ceil(rq/(24*60*60*1000));
	var num = Math.ceil(days/7);
	return num;
}

